package com.tianji.remark;

import cn.hutool.core.collection.CollectionUtil;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.CacheConstants;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.LikedTimesDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LikeRecordSyncToMysqlTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitMqHelper mqHelper;
    @Scheduled(cron = "*/10 * * * * ?")
    public void likeRecordSyncToMysql(){
        log.info("点赞数量同步到数据据任务开始。");
        int pageNo=1;
        while (true){
            Set<ZSetOperations.TypedTuple<String>> typedTuples= redisTemplate.opsForZSet().popMax(CacheConstants.LIKE_COUNT, 100);
            if (CollectionUtil.isEmpty(typedTuples)){
                log.info("没有更多需要同步的数据");
                return;
            }
            List<LikedTimesDTO> msgList = new ArrayList<>();
            for(ZSetOperations.TypedTuple<String>typedTuple:typedTuples){
                //点赞的次数
                Double score = typedTuple.getScore();
                //bizType+":"+bizId
                String value = typedTuple.getValue();
                String[] arr =value.split(":");
                String bizType = arr[0];
                String bizId = arr[1];
                LikedTimesDTO msg = new LikedTimesDTO(Long.parseLong(bizId),score.intValue(),bizType);
                msgList.add(msg);
            }
            Map<String,List<LikedTimesDTO>> msgMap =msgList.stream().collect(Collectors.groupingBy(LikedTimesDTO::getBizType));
            for (Map.Entry<String,List<LikedTimesDTO>> entry :msgMap.entrySet()){
                String bizType = entry.getKey();
                List<LikedTimesDTO> msgs = entry.getValue();
                String key = MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE.replace("{}",bizType);
                mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE,key,msgs);
                log.info("发送第{}页点赞数量的消息，bizType：{}，msgList:{}",pageNo++,bizType,msgs);
            }
        }
    }
}
